#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os,sys
from cmd import Cmd
import _thread as thread
import requests
from config import fsConfig
import json
PATH = os.path.dirname(__file__)
LISTENPATH = "listenService"
LISTENEXEC = "listen.py"
HTTPSERVER = "forwardServer"
HTTPMAIN = "httpserver.py"
JSONHEADERS = {
    "Content-Type": "application/json; charset=UTF-8"
          }
class Cli(Cmd):
    def __init__(self):
        os.system("cls")
        banner = '''
         ____  _____ ______     _____ ____ _____ ____  
        / ___|| ____|  _ \ \   / /_ _/ ___| ____/ ___|
        \___ \|  _| | |_) \ \ / / | | |   |  _| \___ \\
         ___) | |___|  _ < \ V /  | | |___| |___ ___) |
        |____/|_____|_| \_\ \_/  |___\____|_____|____/
        '''
        Cmd.__init__(self)
        self.intro = banner
        self.prompt = 'SafeToolConsole>> '
        self.conf = fsConfig()
    def do_help(self,param):
        print('Help Infomation:')
        print('%-4s%2s%s'%(' ','order: ','listen'))
        print('%-4s%2s%s'%(' ','args: ','@port'))
        print('%-4s%2s%s'%(' ','order: ','set_server_url'))
        print('%-4s%2s%s'%(' ','args: ','@url@port ex:192.168.0.1@3000'))
        print('%-4s%2s%s'%(' ','order: ','help_nmap'))
        print('%-4s%2s%s'%(' ','args: ','none'))
        print('%-4s%2s%s'%(' ','order: ','help_dir_scan'))
        print('%-4s%2s%s'%(' ','args: ','none'))        
    def do_help_nmap(self,param):
        print('%-4s%2s%s'%(' ','order: ','nmap_ping'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_ping_probe'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_ack_probe'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_syn_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_tcp_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_udp_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_fin_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_xmasTree_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_null_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))
        print('%-4s%2s%s'%(' ','order: ','nmap_set_port_range'))
        print('%-4s%2s%s'%(' ','args: ','@ip@port ex:192.169.0.1@50-80'))
        print('%-4s%2s%s'%(' ','order: ','nmap_specify_port_range'))
        print('%-4s%2s%s'%(' ','args: ','@ip@port ex:192.168.0.1@80,81,82'))
        print('%-4s%2s%s'%(' ','order: ','nmap_os_version'))
        print('%-4s%2s%s'%(' ','args: ','@ip'))  
        print('%-4s%2s%s'%(' ','order: ','nmap_all_scan'))
        print('%-4s%2s%s'%(' ','args: ','@ip')) 
        print('%-4s%2s%s'%(' ','order: ','nmap_custom'))
        print('%-4s%2s%s'%(' ','args: ','@cmd ex:nmap -sP 192.168.22.105'))
    def do_help_dir_scan(self,param):
        print('%-4s%2s%s'%(' ','order: ','dir_scan'))
        print('%-4s%2s%s'%(' ','args: ','@urlFileName ex:http[s]://192.168.22.105@reportname.txt'))
        print('%-4s%2s%s'%(' ','order: ','dir_scan_report'))
        print('%-4s%2s%s'%(' ','args: ','@reportName ex:reportName.txt'))        
    def do_listen(self,param):
        if isinstance(int(param),int):
            path = PATH + os.sep + LISTENPATH + os.sep + LISTENEXEC
            os.system("cmd /c start python " + path + " " + param )
        else:
            print("the port number is required !")
    def do_start(self,param:str):
        param = param.strip()
        if param == "http":
            path = PATH + os.sep + HTTPSERVER + os.sep + HTTPMAIN
            cmdSetUp = "cmd /c start python " + path
            wtSetUp = "wt.exe python " + path
            if os.system(wtSetUp) !=0 :
                os.system(cmdSetUp)
        else:
            print("服务不存在!")
    def do_dir_scan(self,urlFileName):
        try:
            url,name = urlFileName.split("@")                
            if url.startswith("http://") or url.startswith("https://"):
                params = {}
                params["url"] = url
                params['name'] = name
                api = "/dirsearch/scan"
                urlpath = self.get_server_url()
                resp = requests.post(url=urlpath+api,data=json.dumps(params),headers=JSONHEADERS)
                print(resp.json())
            else:
                print("url startwith http or https!")                
        except Exception as e:
            print("wrong!")
    def do_dir_scan_report(self,reportName):
        try:
            params = {}
            params["name"] = reportName
            url = self.get_server_url()
            api = "/dirsearch/report"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())                            
        except Exception as e:
            print("wrong!")
    def do_nmap_ping(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/ping"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_ping_probe(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/ping/not/port"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_ack_probe(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/ack"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_syn_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/syn"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_tcp_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/tcp"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_udp_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/udp"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_fin_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/fin"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_xmasTree_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/xmasTree"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_null_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/null"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_set_port_range(self,ipport):
        try:
            ip,port = ipport.split("@")
            params = {}
            params["ip"] = ip
            params["port"] = port
            url = self.get_server_url()
            api = "/nmap/set/port/range"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_specify_port_range(self,ipport):
        try:
            ip,port = ipport.split("@")
            params = {}
            params["ip"] = ip
            params["port"] = port
            url = self.get_server_url()
            api = "/nmap/specify/port/range"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_os_version(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/os/version"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_all_scan(self,ip):
        try:
            params = {}
            params["ip"] = ip
            url = self.get_server_url()
            api = "/nmap/all/scan"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")
    def do_nmap_custom(self,cmd):
        try:
            params = {}
            params["cmd"] = cmd
            url = self.get_server_url()
            api = "/nmap/custom"
            resp = requests.post(url=url+api,data=json.dumps(params),headers=JSONHEADERS)
            print(resp.json())
        except Exception as e:
            print("server wrong!")                                                                                         
    def do_exit(self,param):
        print("Exit!")
        sys.exit()
    def get_server_url(self):
        fullUrl = self.conf.get_url() + ":" + str(self.conf.get_port())
        return fullUrl
    def do_set_server_url(self,urlport):
        url,port = urlport.split("@")
        if not url.startswith("http://"):
            url = "http://" + url
        self.conf.set_url(url)
        self.conf.set_port(port)
    def default(self,param):
        print("order is not exit ! please enter help!")

if __name__ == "__main__":
    try:
        cli = Cli()
        cli.cmdloop()
    except Exception as e:
        print("wrong!")